package com.t2two.example.common.utils;

import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.util.encoders.Hex;

import java.security.Security;
import java.util.Base64;
/**
 * @version 1.0
 * @description: TODO
 * @author: lifei
 * @date: 2025/2/17 9:58
 */
public class SM2DecryptionUtil {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * SM2解密核心方法
     * @param cipherData 密文（ASN.1编码格式）
     * @param privateKeyHex 十六进制格式的私钥
     * @return 解密后的明文
     */
    public static byte[] sm2Decrypt(byte[] cipherData, String privateKeyHex) throws Exception {
        // 将十六进制私钥转换为字节数组
        byte[] privateKeyBytes = Hex.decode(privateKeyHex);

        // 创建SM2私钥参数
        ECPrivateKeyParameters privateKeyParameters = (ECPrivateKeyParameters)
                PrivateKeyFactory.createKey(Hex.decode(privateKeyHex));

        // 创建SM2引擎并初始化为解密模式
        SM2Engine sm2Engine = new SM2Engine();
        sm2Engine.init(false, privateKeyParameters);

        // 执行解密
        try {
            return sm2Engine.processBlock(cipherData, 0, cipherData.length);
        } catch (InvalidCipherTextException e) {
            throw new RuntimeException("SM2解密失败", e);
        }
    }

    /**
     * 两次SM2解密
     * @param encryptedData 原始加密数据
     * @param firstPrivateKey 第一次解密私钥
     * @param secondPrivateKey 第二次解密私钥
     * @return 最终解密结果
     */
    public static String doubleDecrypt(String encryptedData,
                                       String firstPrivateKey,
                                       String secondPrivateKey) throws Exception {
        // 第一次解密
        byte[] firstDecrypted = sm2Decrypt(
                Base64.getDecoder().decode(encryptedData), // 假设数据是Base64编码
                firstPrivateKey
        );

        // 第二次解密
        byte[] secondDecrypted = sm2Decrypt(firstDecrypted, secondPrivateKey);

        return new String(secondDecrypted, "UTF-8");
    }

    public static void main(String[] args) throws Exception {
        // 示例用法
        String interfaceToken = "你的加密参数（Base64格式）";
        String firstPrivateKey = "应用网关的二次核验私钥";
        String secondPrivateKey = "3c57e96dac2d6d0dfd92e400ebb609e584b148b755968d898bd25f2";

        String result = doubleDecrypt(interfaceToken, firstPrivateKey, secondPrivateKey);
        System.out.println("最终解密结果：" + result);
    }
}
